package com.market.cash.ui.presenter

import com.market.cash.configs.CashRootConfigs
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.view.ICashRootHomeView
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.CashRootProcessHelper
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.utils.permission.OnPermissionCallback
import com.market.cash.utils.permission.XXPermissions
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/21 11:59
 * @Annotation：主页 Presenter 实现
 */
class CashRootHomePresenter(private val iView: ICashRootHomeView): ProPresenter(iView) {

    private val CASHROOT_TYPE_GRADE = "TYPE_GRADE"//等级
    private val CASHROOT_TYPE_REPAY_COUNT = "TYPE_REPAY_COUNT"//待还款的产品数量
    private val CASHROOT_TYPE_PRODUCT = "TYPE_PRODUCT"//产品
    private val CASHROOT_TYPE_UNLOCK_TIPS = "TYPE_UNLOCK_TIPS"//解锁提示

    //所有权限
    private var allPermissions: ArrayList<String>? = null
    //选择的产品
    private var selectProduct: JSONObject? = null

    /**
     * 获取所有权限列表
     */
    fun loadCashRootAllPermissionsAction() {
        if (allPermissions == null){
            allPermissions = arrayListOf()
        }
        allPermissions!!.clear()
        Thread{
            val customize = CashRootCustomConfigsHelper.getCashRootConfigData()
            if(customize != null){
                val permissions = customize.optJSONObject("permissions")
                if (permissions != null){
                    val permission = permissions.optJSONArray("permission")
                    if (permission != null && permission.length() > 0){
                        for (i in 0..<permission.length()){
                            allPermissions!!.add(permission.optString(i))
                        }
                    }

                    val home = permissions.optJSONArray("home")
                    if (home != null && home.length() > 0){
                        for (i in 0..<home.length()){
                            val str = home.optString(i)
                            if (allPermissions!!.contains(str)){
                                continue
                            }
                            allPermissions!!.add(str)
                        }
                    }
                }
            }
        }.start()
    }

    /**
     * 加载产品表
     */
    fun loadCashRootProductListAction(){
        val pList = ArrayList<JSONObject>()
        //用户等级item
        pList.add(getCashRootGradeItem())

        //产品数据源
        val pData = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_PRODUCT)

        //待还款产品数量item
        val repayItem = getCashRootRepayCountItem(pData)
        if (repayItem != null){
            pList.add(repayItem)
        }

        //可申请的产品列表
        val list = getCashRootProductList(pData,true)
        if (list != null){
            pList.addAll(list)
        }

        //未解锁产品提示
        pList.add(getCashRootUnlockTipsItem())

        //未解锁产品列表
        val lockList = getCashRootProductList(pData,false)
        if (lockList != null){
            pList.addAll(lockList)
        }
        iView.showCashRootProductList(pList)
    }

    /**
     * 获取用户等级
     */
    private fun getCashRootGradeItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",CASHROOT_TYPE_GRADE)
        item.put("grade",SharedHelper.getCashRootSPInt(SharedHelper.CashRoot_SPKEY.CASHROOT_VIP))
        return item
    }

    /**
     * 获取待还款的产品数量
     */
    private fun getCashRootRepayCountItem(pData: String): JSONObject?{
        if (pData.isNotEmpty()){
            var repayCount = 0
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val obj = objArray.optJSONObject(i)
                val status = obj.optString("status")
                //待还款
                if (status == "REPAYMENT"){
                    repayCount += 1
                }
            }
            if (repayCount > 0){
                val item = JSONObject()
                item.put("itemType",CASHROOT_TYPE_REPAY_COUNT)
                item.put("count",repayCount.toString())
                return item
            }
        }
        return null
    }

    /**
     * 产品列表
     */
    private fun getCashRootProductList(pData: String,isUnlock: Boolean): ArrayList<JSONObject>?{
        if (pData.isNotEmpty()){
            val pList = arrayListOf<JSONObject>()
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                val activeFlag = item.optString("activeFlag")

                //可申请 && 非待还款
                if (isUnlock && activeFlag == "YES" && status != "REPAYMENT"){
                    pList.add(item)
                    continue
                }

                if (!isUnlock && activeFlag != "YES"){
                    pList.add(item)
                }
            }
            return pList
        }
        return null
    }

    /**
     * 获取未解锁产品提示
     */
    private fun getCashRootUnlockTipsItem(): JSONObject{
        val item = JSONObject()
        item.put("itemType",CASHROOT_TYPE_UNLOCK_TIPS)
        return item
    }

    /**
     * 设置申贷的产品
     */
    fun setCashRootSelectProduct(product: JSONObject){
        this.selectProduct = product
    }


    /**
     * 复制主产品信息到目标产品
     */
    private fun onCashRootCopyProductToChildProductAction(targetProduct: String){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path",ApiService.API_PATH.CASHROOT_API_LOAN_PRODUCT_COPY_PATH)
                put("sourceProduct", CashRootConfigs.CASHROOT_APPNAME)
                put("targetProduct", targetProduct)
            }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        doCashRootPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                var pToken = ""
                if (obj != null){
                    pToken = obj.optString("token","")
                }
                if (pToken.isEmpty()){
                    pToken = selectProduct!!.optString("token")
                }
                val pName = selectProduct!!.optString("product")
                iView.showCashRootLoanApplyPage(pName,pToken)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.hideCashRootLoading()
            }
        })
    }

    /**
     * 检查权限是否全部申请
     */
    fun checkCashRootAllPermissionsAgree(){
        if (XXPermissions.isGranted(iView.getAct(),allPermissions!!)){
            iView.showCashRootCheckPermissionSuccess()
            return
        }

        //是否是审核账号
        val isConfigAccount = SharedHelper.getCashRootSPBoolean(SharedHelper.CashRoot_SPKEY.CASHROOT_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，可以进行申贷操作
            iView.showCashRootCheckPermissionSuccess()
            return
        }

        XXPermissions.with(iView.getAct())
            // 申请多个权限
            .permission(allPermissions!!)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        iView.showCashRootCheckPermissionSuccess()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(iView.getAct(),permissions)
                }
            })
    }

    /**
     * 验证认证流程是否完成
     */
    fun checkCashRootAllStepsAction(){
        if (CashRootProcessHelper.getCashRootStepList().size == 0){//流程已完成 - 进入申贷确认页
            val pName = selectProduct!!.optString("product")
            val pToken = selectProduct!!.optString("token")
            //非主产品
            if (pName != CashRootConfigs.CASHROOT_APPNAME){
                //copy 主产品信息到子产品
                onCashRootCopyProductToChildProductAction(pName)
            } else {
                //主产品进入申待确认页
                iView.showCashRootLoanApplyPage(pName,pToken)
            }
        } else {//流程未完成 - 进入 认证步骤页面
            iView.showCashRootProcessStepsPage()
        }
    }
}